import { router, routes as staticRoutes } from "@/router";

import {
	filterAuthRoutesByUserPermission,
	getCacheRoutes,
	transformAuthRouteToMenu,
	transformAuthRouteToVueRoutes,
	transformRoutePathToRouteName,
} from "@/utils";

interface RouteState {
	/**
	 * 权限路由模式:
	 * - static - 前端声明的静态
	 * - dynamic - 后端返回的动态
	 */
	authRouteMode: ImportMetaEnv["VITE_AUTH_ROUTE_MODE"];
	/** 是否初始化了权限路由 */
	isInitAuthRoute: boolean;
	/** 路由首页name(前端静态路由时生效，后端动态路由该值会被后端返回的值覆盖) */
	routeHomeName: AuthRoute.AllRouteKey;
	/** 菜单 */
	menus: App.GlobalMenuOption[];
	/** 搜索的菜单 */
	searchMenus: AuthRoute.Route[];
	/** 缓存的路由名称 */
	cacheRoutes: string[];
}

export const useRouteStore = defineStore("route-store", {
	state: (): RouteState => ({
		authRouteMode: import.meta.env.VITE_AUTH_ROUTE_MODE,
		isInitAuthRoute: false,
		routeHomeName: transformRoutePathToRouteName(
			import.meta.env.VITE_ROUTE_HOME_PATH
		),
		menus: [],
		searchMenus: [],
		cacheRoutes: [],
	}),
	actions: {
		/**
		 * 处理权限路由
		 * @param routes - 权限路由
		 */
		handleAuthRoute(routes: AuthRoute.Route[]) {
			(this.menus as App.GlobalMenuOption[]) = transformAuthRouteToMenu(routes);
			const vueRoutes = transformAuthRouteToVueRoutes(routes);
			vueRoutes.forEach((route) => {
				router.addRoute(route);
			});
			this.cacheRoutes = getCacheRoutes(vueRoutes);
		},
		/**初始化静态路由 */
		async initStaticRoute() {
			const routes = filterAuthRoutesByUserPermission(staticRoutes, "admin");
			this.handleAuthRoute(routes);
			this.isInitAuthRoute = true;
		},
		/** 初始化权限路由 */
		async initAuthRoute() {
			if (this.authRouteMode === "dynamic") {
			} else {
				await this.initStaticRoute();
			}
		},
	},
});
